
import jwt from 'jsonwebtoken';
import { connection } from '../app/database/mysql';
import { PRIVATE_KEY } from '../app/app.config';
import { userModal } from './user.model';
import { APP_URL } from '../app/app.config';
import { selectUserAuth } from '../user_auth/user_auth.service';
import { getByUserIdOrder } from '../order/order.service';
import { getUserVipDay } from '../user_auth/user_auth.service';

/**
 * 用户订单数据
 */
export const userOrder = async (user_id: number) => {
  // 准备查询
  const statement = `
    SELECT * FROM user_auth
    WHERE user_id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, user_id);

  // 提供数据
  return data;
}

/**
 * 获取内容
 */
export const getUser = async (pageSize: number, pageNo: number, userId: number) => {
  // 准备查询
  let statement = `
    SELECT SQL_CALC_FOUND_ROWS *, COUNT(id) OVER () AS total FROM users
  `;

  let where = []
  
  if (userId > 0) {
    where.push(`id = ` + userId)
  }
  if (where.length > 0) {
    statement += ` where `
    for (let i = 0; i < where.length; i++) {
      statement += where[i]
      if (i < where.length - 1) {
        statement += ` and `
      }
    }
  }

  statement += ` ORDER by id DESC, id DESC limit `+(pageNo>0?(pageNo-1)*pageSize:0) + `,` +pageSize
 
  // 执行查询
  const [data] = await connection.promise().query(statement);

  let totalCount: any;
  if (data[0] && data[0].total) totalCount = data[0].total;
  let totalPage = (totalCount % pageSize) > 0 ? parseInt(`${totalCount / pageSize}`) + 1 : totalCount / pageSize;

  // 订单状况
  for (let item of data as any) {
    item.userOrder = await getByUserIdOrder(item.id);
    let vipDayData = await getUserVipDay(item.id);
    item.vipDay = vipDayData.vipTime;
  }

  let res = {
    data,
    totalPage,
    totalCount
  }

  // 提供数据
  return res;
}

/**
 * 模糊查询
 */
export const select_like = async (keyWord: string) => {
  // 准备查询
  const statement = `
    SELECT * FROM \`users\`
    WHERE (id = '${keyWord}' or nickName LIKE '%${keyWord}%')
  `;
  
  // 执行查询
  const [data] = await connection.promise().query(statement, keyWord);

  // 提供数据
  return data;
}

/**
 * 按 openId 获取用户
 */
export const getUserByOpenId = async (openId: number) => {
  // 准备查询
  const statement = `
    SELECT * FROM users
    WHERE openid = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, openId);

  // 提供数据
  return data[0];
}

/**
 * 按 ID 获取 openId
 */
export const getOpenIdByOpenId = async (userId: number) => {
  // 准备查询
  const statement = `
    SELECT openid FROM users
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, userId);

  // 提供数据
  return data[0];
}

/**
 * 按 ID 获取用户
 */
export const getUserById = async (userId: number) => {
  // 准备查询
  const statement = `
    SELECT * FROM users
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, userId);

  // 提供数据
  return data[0];
}

/**
 * 创建内容
 */
export const setUserInfo = async (post: userModal) => {
  // 准备查询
  const statement = `
    INSERT INTO users
    SET ?
  `;
  post.registrationTime = Math.floor(new Date().getTime());

  // 执行查询
  const [data] = await connection.promise().query(statement, post);

  // 提供数据
  return data;
}

/**
 * 签发令牌
 */
interface SignTokenOptions {
  payload?: any;
}

export const SignToken = (options: SignTokenOptions) => {
  // 准备选项
  const { payload } = options;

  // 签发 JWT
  const token = jwt.sign(payload, PRIVATE_KEY, { algorithm: 'RS256' });

  // 提供 JWT
  return token;
}

/**
 * 更新内容
 */
export const updateHouse = async (post: userModal, userId: number) => {
  // 准备查询
  const statement = `
    UPDATE users
    SET ?
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, [post, userId]);

  // 提供数据
  return data;
}

/**
 * 更新内容
 */
export const updateByOpenid = async (post: userModal, openid: number) => {
  // 准备查询
  const statement = `
    UPDATE users
    SET ?
    WHERE openid = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, [post, openid]);

  // 提供数据
  return data;
}
